package com.ruoyi.web.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.AiTopic;
import com.ruoyi.system.domain.vo.AiTopicVo;
import com.ruoyi.system.service.IAiTopicService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户会话topic信息-对外API接口请求处理
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/api/topic")
public class ApiAiTopicController extends BaseController {

    @Autowired
    private IAiTopicService topicService;

    @Log(title = "Topic信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ApiOperation(value = "新增用户会话topic信息")
    public AjaxResult add(@RequestBody AiTopic aiTopic) {
        aiTopic.setUserId(getUserId());
        topicService.insertAiTopic(aiTopic);
        // 新增之后，返回数据
        AiTopic topic = topicService.selectAiTopicById(aiTopic.getId());
        return AjaxResult.success(changeItem(topic));
    }

    @Log(title = "Topic信息", businessType = BusinessType.UPDATE)
    @PostMapping("/update")
    @ApiOperation(value = "修改用户会话topic信息")
    public AjaxResult update(@RequestBody AiTopic aiTopic) {
        return toAjax(topicService.updateAiTopic(aiTopic));
    }

    @GetMapping(value = "/list")
    @ApiOperation(value = "根据sessionId，获取当前用户下的topic列表")
    public AjaxResult list(@RequestParam(value = "sessionId", required = false) String sessionId) {
        AiTopic aiTopic = new AiTopic();
        aiTopic.setSessionId(sessionId);
        aiTopic.setUserId(getUserId());
        List<AiTopic> topicList = topicService.selectAiTopicList(aiTopic);
        if (CollUtil.isEmpty(topicList)) return AjaxResult.success(new ArrayList<>());
        return AjaxResult.success(topicList.stream().map(this::changeItem).collect(Collectors.toList()));
    }

    private AiTopicVo changeItem(AiTopic topic) {
        if (null == topic) return null;
        AiTopicVo resp = new AiTopicVo();
        BeanUtil.copyProperties(topic, resp);
        return resp;
    }
}
